import axios from 'axios'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000, // 请求超时时间
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    console.log('Current token:', token)
    
    if (token) {
      // 确保token格式正确：Bearer + token
      config.headers['Authorization'] = `Bearer ${token}`
      console.log('Request headers:', config.headers)
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 如果响应中包含token，自动保存
    if (response.data && response.data.token) {
      localStorage.setItem('token', response.data.token)
      console.log('Token saved:', response.data.token)
    }
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.log('Token expired or invalid, redirecting to login')
          localStorage.removeItem('token')
          router.push('/login')
          break
        case 403: // 权限不足
          console.error('权限不足')
          break
        case 404: // 请求不存在
          console.error('请求的资源不存在')
          break
        case 500: // 服务器错误
          console.error('服务器错误')
          break
        default:
          console.error(`其他错误：${error.response.status}`)
      }
    }
    return Promise.reject(error)
  }
)

// 封装GET请求
export const get = (url, params) => {
  return service({
    method: 'get',
    url,
    params
  })
}

// 封装POST请求
export const post = (url, data) => {
  return service({
    method: 'post',
    url,
    data
  })
}

// 封装PUT请求
export const put = (url, data) => {
  return service({
    method: 'put',
    url,
    data
  })
}

// 封装DELETE请求
export const del = url => {
  return service({
    method: 'delete',
    url
  })
}

export default service 